
<!--
业务提单
 -->
<template>
<div class="businessform">
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/initiatingprocess' }" v-if="isShowItem">{{process[processNumber]}}</el-breadcrumb-item>
      <span @click.stop=";" v-if="isShowSpan">{{process[processNumber]}} <i class="el-icon-arrow-right"></i></span>
      <span @click.stop=";">业务提单</span>
    </el-breadcrumb>
  </div>

  <el-tabs v-model="editableTabsValue" type="card" @tab-click="clickTabs">

    <el-tab-pane :key="item.name" v-for="(item, index) in editableTabsFixed" :label="item.title" :name="item.name">
      <business-check-form ref="checkform" :editable="saveData.roles.businessform_businesscheckform == 'W'" :businessformNO="saveData.businessform_no" :data="saveData.businessform_businesscheckform" :formId="formIdStart + '_' + item.formId" v-if="item.name == '1'" />


      <profitCalculation ref="profit" :relation="relation" :editable="saveData.roles.businessform_profitcalculation == 'W'" :businessformNO="saveData.businessform_no" :data="saveData.businessform_profitcalculation" :relatedData1="saveData.businessform_pi" :fromOther="fromOther" :relatedData2="saveData.businessform_foreigntradecontract"
        :relatedData3="saveData.businessform_domestictradecontract" :formId="formIdStart + '_' + item.formId" v-else-if="item.name == '100'" />


      <foreign-trade-contract ref="foreign" :relation="relation" :editable="saveData.roles.businessform_foreigntradecontract == 'W'" :businessformNO="saveData.businessform_no"  :relatedData1="saveData.businessform_businesscheckform" :data="saveData.businessform_foreigntradecontract" :fromOther="fromOther" :formId="formIdStart + '_' + item.formId" v-else-if="item.name == '2'"
      />

      <pi :relation="relation" :fromOther="fromOther"  ref="pi" :businessformNO="saveData.businessform_no" :editable="saveData.roles.businessform_pi == 'W'" :data="saveData.businessform_pi" :relatedData="saveData.businessform_foreigntradecontract" :formId="formIdStart + '_' + item.formId"
        v-else-if="item.name == '3'" />

      <template v-else-if="item.name == '4'">
          <span v-if="saveData.roles.businessform_domestictradecontract =='W'" slot="label"><i @click="addTab" class="operation-icon  el-icon-circle-plus"></i>{{item.title}}</span>
          <domestic-trade-contract ref="dom1" :index="index" :relation="relation" :editable="saveData.roles.businessform_domestictradecontract == 'W'"  :businessformNO="saveData.businessform_no" :data="dtcs[0]" :fromOther="fromOther" :relatedData="saveData.businessform_foreigntradecontract"  :formId="formIdStart + '_' + item.formId" />
        </template>

      <template v-else>
          <span v-if="saveData.roles.businessform_domestictradecontract =='W'"  slot="label"><i @click="removeTab(index)"  class="operation-icon  el-icon-circle-close"></i>{{item.title}}</span>

          <!-- 利用index确定当前是哪个内贸合同 index - 4 的值对应于内贸合同数组中的对应内贸合同 -->
          <domestic-trade-contract :index="index"  :relation="relation" :editable="saveData.roles.businessform_domestictradecontract == 'W'" :fromOther="fromOther" :businessformNO="saveData.businessform_no" :data="dtcs[index - 3]" :relatedData="saveData.businessform_foreigntradecontract" :formId="formIdStart + '_' + item.formId" />
        </template>
    </el-tab-pane>
  </el-tabs>

  <div class="businessform-fixed">
    <fixed-form ref="fixedForm" :fromOther="fromOther" :saveAndSend="saveAndSend" :editable="editable" :saveData="saveData" :sendMenus="sendMenus" processName="businessform" />
  </div>
</div>
</template>

<script>
import businessCheckForm from './components/businessCheckForm.vue'
import profitCalculation from './components/profitCalculation.vue'
import foreignTradeContract from './components/foreignTradeContract.vue'
import pi from './components/pI.vue'
import domesticTradeContract from './components/domesticTradeContract.vue'
import fixedForm from '../common/fixedForm.vue'

import {
  setStore,
  getStore
} from '@/assets/js/common'


import {
  getData,
  getSendMenus,
  getOrderNumber,
} from '@/server/initiatingprocess';

export default {
  created() {
    this.sendMenus = [];

    this.saveData = {
      roles: {
        businessform_businesscheckform: 'W',
        businessform_foreigntradecontract: 'W',
        businessform_pi: 'W',
        businessform_domestictradecontract: 'W',
        businessform_profitcalculation: 'W',
      },
    };

    let state = _.cloneDeep(this.$store.state.businessform);

    for (var prop in state) {
      this.saveData[prop] = state[prop];
    }

    this.dtcs = this.saveData.businessform_domestictradecontract;
  },
  mounted() {
    //刷新浏览器时，避免重叠
    document.querySelector('.initiatingprocess  .routers-ctrl').style.zIndex = '-1';


    let date = new Date();
    let m = date.getMonth() + 1;
    let d = date.getDate();
    m = m < 10 ? '0' + m : m;
    d = d < 10 ? '0' + d : d;



    //获得订单编号
    getOrderNumber({
      year: date.getFullYear()
    }).then((res) => {
      let businessform_no = "NO.DD" + date.getFullYear() + m + d + res;
      this.saveData.businessform_no = businessform_no;


      //获得相关数据
      getSendMenus({
        'flowId': 1
      }).then((response) => {
        this.sendMenus = response.data.datas[0];
        this.$forceUpdate();
      });

    });

    //判断面包屑二级路由是否可退回
    let isCreatFlow = getStore('isCreatFlow');
    this.isShowItem = !isCreatFlow ? false : true;
    this.isShowSpan = !isCreatFlow ? true : false;

  },
  beforeUpdate() {
  },

  updated(){
  },

  beforeRouteEnter(to, from, next) {
    next(vm => {
      let temp = vm.$children[1];
      vm.editableTabsValue = '' + to.query.tab;

      switch (vm.editableTabsValue) {
        case '1':
        vm.$refs.checkform[0].data.hasClicked = true;
        break;
        case '2':
        vm.$refs.foreign[0].data.hasClicked = true;
        break;
        case '3':
        vm.$refs.pi[0].data.hasClicked = true;
        break;
        case '4':
        vm.$refs.dom1[0].data.hasClicked = true;
        break;
        case'100':
        vm.$refs.profit[0].data.hasClicked = true;
        break;
      }


      //从其他事项中跳转过来，从服务端获得数据而不是从头填写
      if (to.query.dTab) {

        //后端的查询依赖 formInstId  formServiceName
        //formInstId=2&formServiceName=business_lading
        vm.editableTabsValue = '' + to.query.dTab;

        //给子组件传递 一个额外的props  relatoin并且此时的值为false, 也就是数据没有关联
        // vm.relation = false;
        vm.relation = true;

        vm.processNumber = parseInt(to.query.itemStatus);

        vm.fromOther = true;


        let params = {
          flowId: to.query.flowId,
          currNodeId: to.query.currNodeId
        };

        if (to.query.isHive == 1) {
          vm.$store.commit('businessform/SET_SAVE');
          getData({
            formInstId: to.query.formInstId,
            formServiceName: to.query.formServiceName,
            isHive: 1
          }).then((response) => {

            let data = response.data.datas[0];

            //对其中的字符串类型的附件名称，进行分割
            data = JSON.parse(JSON.stringify(data).replace(/(attachedFiles)/g, function() {
              return 'useless01';
            }).replace(/(attachedFileList)/g, function() {
              return "attachedFiles";
            }).replace(/(relationFormInst)/g, function(){ return 'relationFormInstId'}), function(k, v) {
              if (k === 'attachedFiles') {
                if (Array.isArray(v)) {
                  return v.map((e) => {
                    return {
                      name: e.realFileName,
                      status: 1,
                      id: e.id
                    };
                  });
                } else {
                  return [];
                }
              }

              /*
              关联订单修改了为单选
              if (k === 'relationFormInstId'){
                if (!_.isArray(v)){
                  return [];
                }
              }
              */

              if (k === 'relationFormInstId'){
                if (_.isPlainObject(v)){
                  return [v];
                } else {
                  return [];
                }
              }
              return v;
            });


            _.extend(vm.saveData, data);

            vm.dtcs = vm.saveData.businessform_domestictradecontract;

            for (let i = 0, len = vm.saveData.businessform_domestictradecontract.length - 1; i < len; i++) {
              //考虑有多个内贸合同
              //this.onlyAddTab()，根据个数决定调用 n - 1 次, 添加tab
              vm.onlyAddTab();
            }


            let approvalIndex, approvalFullName, names = [];

            if (data.role) {

              for (var prop in vm.saveData.roles) {
                vm.saveData.roles[prop] = data.role.DEFAULT;
              }

              vm.editable = (data.role.DEFAULT == 'W') ? true : false;
              vm.saveAndSend = vm.editable;

              ////////

              let copyApprovals = _.cloneDeep(data.approvals);

              // copyApprovals.forEach(e => {
              //   let str = e.approval_div_name;
              //   e.approval_div_name = vm.saveData.approvalNames[Number(str[str.length - 1]) - 1];
              // });

              for (let i = 0; i < copyApprovals.length; i++) {
                for (var prop in vm.saveData.originApprovals[i]) {
                  if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')) {
                    vm.saveData.originApprovals[i][prop] = copyApprovals[i][prop]
                  }
                }
              }

              vm.saveData.isSalesMan = false;
            } else {
              vm.saveData.isSalesMan = true;
            }

            vm.saveData.businessform_profitcalculation.bpc_table2.forEach((e, i) => {
              if (i === 0) {
                e.bpc_table2_first = true;
              }
            });

            vm.saveData.businessform_no = data.orderCode;



            getSendMenus(params).then((response) => {
              vm.sendMenus = response.data.datas[0];


              vm.$forceUpdate();
              vm.$refs.fixedForm.isForceUpdate = true;
              vm.$refs.fixedForm.$forceUpdate();
            });

          });
        } else {

          getData({
            formInstId: to.query.formInstId,
            formServiceName: to.query.formServiceName
          }).then((response) => {

            let data = response.data.datas[0];



            //对其中的字符串类型的附件名称，进行分割
            data = JSON.parse(
              JSON.stringify(data).replace(/(attachedFiles)/g, function() {
                return 'useless01';
              }).replace(/(attachedFileList)/g, function() {
                return "attachedFiles";
              }).replace(/(relationFormInst)/g, function(){ return 'relationFormInstId'}),
              function(k, v) {
                if (k === 'attachedFiles') {
                  if (Array.isArray(v)) {
                    return v.map((e) => {
                      return {
                        name: e.realFileName,
                        status: 1,
                        id: e.id
                      };
                    });
                  } else {
                    return [];
                  }
                }

                if (k === 'relationFormInstId'){
                  if (_.isPlainObject(v)){
                    return [v];
                  } else {
                    return [];
                  }
                }

                return v;
              });


            _.extend(vm.saveData, data);

            vm.saveData.businessform_pi.hasClicked = true;
            vm.saveData.businessform_profitcalculation.hasClicked = true;
            vm.saveData.businessform_domestictradecontract.forEach(e => {
              e.hasClicked = true;
            });


            vm.dtcs = vm.saveData.businessform_domestictradecontract;

            for (let i = 0, len = vm.saveData.businessform_domestictradecontract.length - 1; i < len; i++) {
              //考虑有多个内贸合同
              //this.onlyAddTab()，根据个数决定调用 n - 1 次, 添加tab
              vm.onlyAddTab();
            }


            let approvalIndex, approvalFullName, names = [];

            if (data.role) {
              data.role.forEach((e) => {
                if (e.itemName.indexOf("item") === -1) {
                  vm.saveData.roles[e.itemName] = e.permission;
                } else {
                  let num = Number(e.itemName[e.itemName.length - 1]) - 1;
                  if (e.permission == 'W') {
                    approvalIndex = num;
                    approvalFullName = e.itemName;
                  }
                }
              });

              vm.editable = vm.saveData.roles.businessform_businesscheckform == 'W' ? true : false;
              vm.saveAndSend = true;

              ///////

              let copyApprovals = _.cloneDeep(data.approvals);

              // copyApprovals.forEach(e => {
              //   let str = e.approval_div_name;
              //   e.approval_div_name = vm.saveData.approvalNames[Number(str[str.length - 1]) - 1];
              // });
              if (approvalIndex !== undefined) {

                if (approvalIndex >= 0) {

                  for (let i = 0; i <= approvalIndex; i++) {

                    if (copyApprovals[i]) {
                      for (var prop in vm.saveData.originApprovals[i]) {
                        if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')) {
                          vm.saveData.originApprovals[i][prop] = copyApprovals[i][prop]
                        }
                      }
                      vm.saveData.originApprovals[i].approval_id = '' + copyApprovals[i].id;
                    }
                  }
                }

                let date = new Date();
                vm.saveData.originApprovals[approvalIndex].rw = 'W';
                vm.saveData.originApprovals[approvalIndex].approval_time = date.toLocaleDateString() + ' ' + date.toTimeString().slice(0, 9);
                vm.saveData.originApprovals[approvalIndex].approval_username = JSON.parse(getStore('userMsg')).userName;;

              } else if (copyApprovals.length > 0) {
                for (let i = 0; i < copyApprovals.length; i++) {

                  for (var prop in vm.saveData.originApprovals[i]) {
                    if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')) {
                      vm.saveData.originApprovals[i][prop] = copyApprovals[i][prop]
                    }
                  }
                  vm.saveData.originApprovals[i].approval_id = '' + copyApprovals[i].id;
                }
              }


              //////

              vm.saveData.isSalesMan = false;
              /*

                    vm.saveData.prevApprovals = _.cloneDeep(data.approvals);

                    vm.saveData.prevApprovals = vm.saveData.prevApprovals.filter(e => {
                      return (e.approval_username != '' && e.approval_username != null);
                    });


                    if (approvalIndex !== undefined) {
                      vm.saveData.newApproval.approval_div_name = approvalFullName;
                      let date = new Date();
                      vm.saveData.newApproval.approval_time = date.toLocaleDateString() + ' ' + date.toTimeString().slice(0, 9);
                      vm.saveData.newApprovalName = vm.saveData.approvalNames[approvalIndex];
                    } else {
                      vm.saveData.newApprovalName = "";
                    }


                    if (vm.saveData.prevApprovals.length > 0) {
                      names = vm.saveData.prevApprovals.map((e) => {
                        let str = e.approval_div_name;
                        return vm.saveData.approvalNames[Number(str[str.length - 1] - 1)];
                      });
                    }

                    if (approvalIndex !== undefined) {
                      names.push(vm.saveData.approvalNames[approvalIndex]);
                    }
                    //["xx审批", "yyy审批"]

                    vm.saveData.prevApprovals.forEach(e => {
                      let str = e.approval_div_name;
                      e.approval_div_name = vm.saveData.approvalNames[Number(str[str.length - 1]) - 1];
                    });


                    vm.saveData.remainApprovals = vm.saveData.approvalNames.filter((e) => {
                      return names.indexOf(e) == -1;
                    });
                    //["zzz审批"]
                    */

              vm.saveData.businessform_no = data.orderCode;

            } else {
              // vm.saveData.approvals = _.cloneDeep(vm.$store.state.businessform.approvals);
              vm.saveData.isSalesMan = true;
            }

            vm.saveData.businessform_profitcalculation.bpc_table2.forEach((e, i) => {
              if (i === 0) {
                e.bpc_table2_first = true;
              }
            });

            

            getSendMenus(params).then((response) => {
              vm.sendMenus = response.data.datas[0];

              vm.$forceUpdate();
              vm.$refs.fixedForm.isForceUpdate = true;
              vm.$refs.fixedForm.$forceUpdate();
            });

          });
        }

      }


      //当用户直接点击某个tab页进入该流程时，就直接使用空值，不再使用关联的值
      if (vm.editableTabsValue == '100'){
        temp.$children[temp.$children.length - 1].$children[0].clickTimes = 2;
      } else {
        temp.$children[vm.editableTabsValue].$children[0].clickTimes = 2;
      }
    })
  },
  beforeRouteLeave(to, from, next){
    document.querySelector('.initiatingprocess  .routers-ctrl').style.zIndex = '-1';
    if (!this.$store.state.businessform.hasSaved){
      this.$confirm('您填写的内容尚未保存或发送,是否要离开?', '提示', {
        confirmButtonText: '离开',
        cancelButtonText: '留下',
        type: 'warning'
      }).then(() => {
        next();
      }).catch(() => {
        Array.prototype.forEach.call(document.getElementsByTagName('*'), (e) => {
          e.blur();
        });
        next(false);
      });
    } else {
      next();
    }
  },
  data() {
    return {
      saveData: {},
      isShowItem: false,
      isShowSpan: false,
      relation: true, //决定表格之间是否有关联，当从服务器端获取数据时，所有的表格都不会有关联,
      editableTabsValue: '1',
      editable: true,
      saveAndSend: true,
      process: ['待发事项', '待办事项', '已办事项', '发起流程'],
      processNumber: 3,
      addStartName: 5,
      editableTabsFixed: [{
        title: '业务审核表',
        name: '1',
        formId: 'businesscheckform'
      }, {
        title: '外贸合同',
        name: '2',
        formId: 'foreigntradecontract'
      }, {
        title: 'PI',
        name: '3',
        formId: 'pi'
      }, {
        title: '内贸合同',
        name: '4',
        formId: 'domestictradecontract'
      }, {
        title: '利润测算表',
        name: '100',
        formId: 'profitcalculation'
      }],
      fromOther: false
    }
  },
  props: {
    formIdStart: {
      type: String,
      required: true
    }
  },
  components: {
    businessCheckForm,
    profitCalculation,
    foreignTradeContract,
    pi,
    domesticTradeContract,
    fixedForm
  },
  methods: {
    onlyAddTab() {
      //解决从server获得数据时，内贸合同有数据但是没tab的问题
      let tempLen = this.editableTabsFixed.length;
      this.editableTabsFixed.splice(tempLen - 1, 0, {
        title: '内贸合同',
        formId: 'domestictradecontract',
        name: '' + this.addStartName
      })
      this.addStartName++;
    },
    addTab() {
      let tempLen = this.editableTabsFixed.length;
      this.editableTabsFixed.splice(tempLen - 1, 0, {
        title: '内贸合同',
        formId: 'domestictradecontract',
        name: '' + this.addStartName
      })

      this.addStartName++;

      let newDtc = _.cloneDeep(this.dtcs[0])
      newDtc.bd_no = newDtc.bd_no.replace(/-(\d+)$/, function(match, p1){
          let n = Number(p1) + 1;
          return '-' + n;
      });

      this.dtcs.push(newDtc);
      this.saveData.businessform_domestictradecontract = this.dtcs;
      this.$forceUpdate();
    },

    removeTab(index) {
      this.editableTabsFixed.splice(index, 1);
       this.dtcs.splice(index - 3, 1);

       this.saveData.businessform_domestictradecontract = this.dtcs;

      setTimeout(function() {
        let allTabs = document.querySelectorAll('.businessform div[role=tab]');
        allTabs[allTabs.length - 1].click();
      }, 0)
    },
    clickTabs(curTab) {

      /*
      //当一个tab页第一次被点击时强制update
      */
      if (curTab.$children[0].clickTimes === 0) {
        curTab.$children[0].clickTimes++;
        curTab.$children[0].$forceUpdate();
      }

      curTab.$children[0].clickTab = true;
      curTab.$children[0].clickTableIndex = -1;
      curTab.$children[0].data.hasClicked = true;
      curTab.$children[0].$forceUpdate();
    },
    specialInitialProcess(event) {
      let cls = event.target.classList;
      if (cls.contains("el-icon-arrow-right") && cls.contains("el-breadcrumb__separator")) {
        return;
      }

      let dom = document.querySelector('.initiatingprocess .routers-ctrl');
      if (dom) {
        dom.style.zIndex = '0';
      }
    }
  }
}
</script>


<style lang="scss">
.businessform {

    padding: 20px;

    i.el-breadcrumb__separator {
        margin: 0 !important;
    }

    i.el-breadcrumb__separator[class*=icon] {
        margin: 0 !important;
        padding: 0 9px !important;
    }

    .operation-icon {
        position: absolute;
        right: 3px;
        top: 50%;
        transform: translate(0, -50%);
    }

    .businessform-fixed {
        border: 1px solid #999;
        margin-top: 20px;
    }
}
</style>
